﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using thinger.VisionModels;
using thinger.VisitionDAL;
using SASJL;
using Vision.Camera.HK;
using MC;
using Station.Common.Rejudgment;
using Station.Inspect.Rejudgment;
using HalconDotNet;
using Station.Inspect;
using System.Threading;

namespace thinger.VisionDemo
{
    public class GlobalVar
    {
        private static GlobalVar instance;

        private static object instanceLock = new object();
        public static GlobalVar Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (instanceLock)
                    {
                        if (instance == null)
                        {
                            instance = new GlobalVar();
                        }
                    }
                }
                return instance;
            }
        }
        //
        public Thread inintThread;   //初始化线程
        public Thread thread1;
        public Thread thread2;
        public bool ThreadControl;
        public OrderData OrderData1 = new OrderData();
        public OrderData OrderData2 = new OrderData();
        public plcStep currplc_step1 = 0;
        public plcStep currplc_step2 = 0;
        public int linenumCH = 0;
        public H5U h5uPLC = new H5U();
        //--- 耗时 运动 时间计算
        //开始 结束时间
        public TimeStepData TimeStepData1;
        public TimeStepData TimeStepData2;
        //-----   -----  机器人
        public bool inintRobot;
        public bool isPanRun;
        public int go_type;
        public int robot_quliao_count = 1;
        public int robot_okliao_count = 1;
        public robot_shang_Step robot_quliao_Step = 0;
        public robot_xia_Step robot_xialiao_Step = 0;
        public HikHelper camera1 = new HikHelper();
        public ShapeModelHelper shapeModel = new ShapeModelHelper();
        public HTuple hWindowHandle = new HTuple();
        public HObject hImage = new HObject();
        public MatchParams getMatchParams = new MatchParams();

        //模板相关
        public HTuple homMat2D = new HTuple();
        public HTuple homMat2D_dama_a1 = new HTuple();
        public HTuple homMat2D_dama_b1 = new HTuple();
        public HTuple homMat2D_dama_a2 = new HTuple();
        public HTuple homMat2D_dama_b2 = new HTuple();
        public string CalibrationBasePath = Application.StartupPath + "\\Calibration";
        public string SaveBasePath = Application.StartupPath + "\\SaveImage";
        public CircleParams getCircleParams = new CircleParams();
        public CalibrationHelper calibration = new CalibrationHelper();
        public bool dama_ison;
        public string damaMode;
        public string damaStr = "";
        public string dumaStr = "";
        //模板
        public string ModelBasePath = Application.StartupPath + "\\Model";
        public string ModelBasePathNew = Application.StartupPath + "\\Model";
        //检测相关数据
        public bool DoReCheck = false; //复判是否完成
        public bool getFinished;//接收检测数据完成
        public CellInfo[] cellInfos_1;
        public CellInfo[] cellInfos_2;
        public List<ErrList> comInfos_1 = new List<ErrList>();//
        public List<ErrList> comInfos_2 = new List<ErrList>();//
        //读码                                               
        public bool isReadOn;
        public string dumaCoder;
        //
        public bool CurrPutType1;
        public int total;
        //纠偏报错
        public bool isFullNG = false;
        public bool isReToNG = false;
        public bool isReadWarn = false;
        public bool isOpneWarn = false;
        public bool IsPause = false;

        //用户权限
        public SysAdmins sysAdmins;
        public bool isProInit;
        //
        public string chloadPath;//当前托盘拍照位置

        //全局变量
        public int CurrNumT = 0;//当前托盘拍照位置
        public int CurrNumNG = 0;//当前托盘NG位置
        public int CurrNumOK = 0;//当前托盘OK位置
        public int CurrNumTMax = 0;//当前托盘拍照最大点阵数
        public int CurrNumNGMax = 0;//当前托盘NG最大点阵数
        public int CurrNumOKMax = 0;//当前托盘OK最大点阵数
        //
        public List<RobotData> QUDatas = new List<RobotData>();
        public List<RobotData> OKDatas = new List<RobotData>();
        public List<RobotData> NGDatas = new List<RobotData>();
        public string CurrentTime
        {
            get { return DateTime.Now.ToString("HH:mm:ss"); }
        }
        //获取码 搬运变量
        public string Coder_1 = string.Empty;
        public string Coder_2 = string.Empty;
        //打码参数设置
        public bool connectDama = false;
        //扫码
        public bool connectDuma = false;
        //初始化判断  机器人完成后才进行plc
        //机器人
        public bool connectRobot = false;
        //PLC
        public bool connectPLC = false;
        public string plcIP = string.Empty;
        //mes 相机 数据
        public bool connectMES = false;
        public bool connectCamera1 = false;
        public bool connectCamera2 = false;
        public bool connectData = false;

        //线程关闭 停止运行相关
        public void WriteTXT_StreamWriter(string pathAName, string txtContent)
        {
            FileStream fs;
            //判断是否已经有了这个文件
            if (!System.IO.File.Exists(pathAName))
            {
                //没有则创建这个文件,创建写入文件，设置文件属性为隐藏
                fs = new FileStream(pathAName, FileMode.Create, FileAccess.Write);
            }
            else
            {
                //调用File类的Delete()方法删除C盘根目录下的Test.txt文本文件
                System.IO.File.Delete(pathAName);
                //fs = new FileStream(pathAName, FileMode.Open, FileAccess.Write);
                fs = new FileStream(pathAName, FileMode.Create, FileAccess.Write);
            }
            File.SetAttributes(@pathAName, FileAttributes.Hidden);
            StreamWriter sw = new StreamWriter(fs);
            try
            {
                sw.WriteLine(txtContent.Trim());//写入值
            }
            finally
            {
                sw.Flush();
                sw.Dispose();
                sw.Close();
                fs.Close();
            }
        }
        //---- 
        public static CameraHK camera;
        public static MC.MCLeisai mc;
        //public static RobotBase rbt;
        public static void Init()
        {
            bool rc = true;
            mc = new MC.MCLeisai();
            mc.Init();
            mc.SetDO(1, 0);
            camera = new CameraHK();
            rc = camera.OpenByIP("192.168.66.1", "192.168.66.10");
            if (rc == false)
            {
                MessageBox.Show("相机连接失败");
            }
        }
        public static void UInit()
        {
            camera.CloseCam();
        }

        //------------
        /// <summary>
        /// 唯一code
        /// </summary>
        /// <returns></returns>
        public string getCoderStr(SysConfig sysConfig)
        {
            string str = "";
            if (string.IsNullOrEmpty(sysConfig.dama_model_name) || string.IsNullOrEmpty(sysConfig.dama_user_code) || string.IsNullOrEmpty(sysConfig.dama_pici) || string.IsNullOrEmpty(sysConfig.dama_liushui) || string.IsNullOrEmpty(sysConfig.dama_ver) || string.IsNullOrEmpty(sysConfig.dama_numer_liushui.ToString()))
            {
                return "";
            }
            else
            {
                int m = Convert.ToInt32(sysConfig.dama_liushui);
                m += sysConfig.dama_numer_liushui;
                if (m > 999)
                {
                    return "";
                }
                int totalLength = 3;
                string mStr = m.ToString().PadLeft(totalLength, '0');
                str = sysConfig.dama_model_name + sysConfig.dama_user_code + sysConfig.dama_pici + mStr + sysConfig.dama_ver;
                sysConfig.dama_liushui = mStr;
            }

            return str;
        }

        public static string getTempStr()
        {
            //var unixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
            //return unixTimestamp.ToString();
            long t = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
            return t.ToString();
        }

        public string GetEditMapping(SysConfig sysConfig, CellInfo[] cellInfos, OrderData ordata)
        {
            string doReplace(string str, string oldStr, string newStr)
            {
                if (str.IndexOf(oldStr) > -1)
                {
                    str = str.Replace(oldStr, newStr);
                }
                return str;
            }

            int ok = 0, ng = 0, oktotal = 0, ngtotal = 0, total = 0, atotal = 0, btotal = 0, aok = 0, ang = 0, bok = 0, bng = 0, conut = 0;
            string time = "", data = "", adata = "", bdata = "";

            if (!sysConfig.chc_mapping)
            {
                return "";
            }
            //---------- domapping
            int dddd = sysConfig.numer_check_col * sysConfig.numer_check_row;
            if (!string.IsNullOrEmpty(ordata.Code))
            {
                if (cellInfos.Length > 0)
                {
                    for (int i = 0; i < cellInfos.Length; i++)
                    {
                        if (i > dddd - 1)
                        {
                            break;
                        }
                        else
                        {
                            if (i == 0)
                            {
                                if (!string.IsNullOrEmpty(sysConfig.frontdata))
                                {
                                    data += sysConfig.frontdata;
                                    adata += sysConfig.frontdata;
                                    bdata += sysConfig.frontdata;
                                    conut++;
                                }

                            }
                            int m = (i + 1) % sysConfig.numer_check_col;
                            if (cellInfos[i].IsNG)
                            {
                                if (string.IsNullOrEmpty(sysConfig.ngcode))
                                {
                                    data += "0";
                                }
                                else
                                {
                                    data += sysConfig.ngcode;
                                }
                                ng++;
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(sysConfig.okcode))
                                {
                                    data += "1";
                                }
                                else
                                {
                                    data += sysConfig.okcode;
                                }
                                ok++;

                            }

                            if (cellInfos[i].DicCell.ContainsKey("A"))
                            {
                                if (cellInfos[i].DicCell["A"].Status == CellStatus.NG)
                                {
                                    if (string.IsNullOrEmpty(sysConfig.ngcode))
                                    {
                                        adata += "0";
                                    }
                                    else
                                    {
                                        adata += sysConfig.ngcode;
                                    }

                                    ang++;
                                    ngtotal++;
                                }
                                else
                                {
                                    if (string.IsNullOrEmpty(sysConfig.okcode))
                                    {
                                        adata += "1";
                                    }
                                    else
                                    {
                                        adata += sysConfig.okcode;
                                    }
                                    aok++;
                                    oktotal++;
                                }
                            }
                            if (cellInfos[i].DicCell.ContainsKey("B"))
                            {
                                if (cellInfos[i].DicCell["B"].Status == CellStatus.NG)
                                {
                                    if (string.IsNullOrEmpty(sysConfig.ngcode))
                                    {
                                        bdata += "0";
                                    }
                                    else
                                    {
                                        bdata += sysConfig.ngcode;
                                    }
                                    bng++;
                                    ngtotal++;
                                }
                                else
                                {
                                    if (string.IsNullOrEmpty(sysConfig.okcode))
                                    {
                                        bdata += "1";
                                    }
                                    else
                                    {
                                        bdata += sysConfig.okcode;
                                    }
                                    bok++;
                                    oktotal++;
                                }
                            }
                            if (m == 0)
                            {
                                data += "\n";
                                adata += "\n";
                                bdata += "\n";
                                if (!string.IsNullOrEmpty(sysConfig.frontdata) && conut < sysConfig.numer_check_row)
                                {
                                    data += sysConfig.frontdata;
                                    adata += sysConfig.frontdata;
                                    bdata += sysConfig.frontdata;
                                    conut++;
                                }

                            }
                        }
                    }
                }
                atotal = aok + ang;
                btotal = bok + bng;
                total = atotal + btotal;
            }

            //---- mapping 替换
            string text = LogRecord.GetReadTxt(Application.StartupPath + "\\mapping\\mapping.txt");
            //--------常规替换-------------
            text = doReplace(text, "{protype}", sysConfig.dama_model_name);
            text = doReplace(text, "{usercode}", sysConfig.dama_user_code);
            text = doReplace(text, "{lotnid}", sysConfig.dama_liushui);
            text = doReplace(text, "{lotnum}", sysConfig.dama_pici);
            text = doReplace(text, "{vernum}", sysConfig.dama_ver);
            //---
            text = doReplace(text, "{pcb}", sysConfig.txt_gong_type);
            text = doReplace(text, "{userpcb}", sysConfig.txt_ke_type);
            text = doReplace(text, "{lotcode}", sysConfig.lotcode);
            text = doReplace(text, "{okcode}", sysConfig.okcode);
            text = doReplace(text, "{ngcode}", sysConfig.ngcode);
            //---
            text = doReplace(text, "{cellx}", sysConfig.cellx);
            text = doReplace(text, "{celly}", sysConfig.celly);
            text = doReplace(text, "{stepx}", sysConfig.stepx);
            text = doReplace(text, "{stepy}", sysConfig.stepy);
            //---
            text = doReplace(text, "{row}", sysConfig.numer_check_row.ToString());
            text = doReplace(text, "{col}", sysConfig.numer_check_col.ToString());
            //---拓展变量
            text = doReplace(text, "{var1}", sysConfig.var1);
            text = doReplace(text, "{var2}", sysConfig.var2);
            text = doReplace(text, "{var3}", sysConfig.var3);
            text = doReplace(text, "{var4}", sysConfig.var4);
            text = doReplace(text, "{var5}", sysConfig.var5);
            text = doReplace(text, "{var6}", sysConfig.var6);
            text = doReplace(text, "{var7}", sysConfig.var7);
            text = doReplace(text, "{var8}", sysConfig.var8);
            text = doReplace(text, "{var9}", sysConfig.var9);
            text = doReplace(text, "{var10}", sysConfig.var10);
            text = doReplace(text, "{var11}", sysConfig.var11);
            text = doReplace(text, "{var12}", sysConfig.var12);

            //---mapping重要变量
            text = doReplace(text, "{ok}", ok.ToString());
            text = doReplace(text, "{ng}", ng.ToString());
            text = doReplace(text, "{oktotal}", oktotal.ToString());
            text = doReplace(text, "{ngtotal}", ngtotal.ToString());

            //---
            text = doReplace(text, "{code}", ordata.Code);
            //
            text = doReplace(text, "{total}", total.ToString());
            text = doReplace(text, "{atotal}", atotal.ToString());
            text = doReplace(text, "{btotal}", btotal.ToString());
            text = doReplace(text, "{aok}", aok.ToString());
            text = doReplace(text, "{ang}", ang.ToString());
            text = doReplace(text, "{bok}", bok.ToString());
            text = doReplace(text, "{bng}", bng.ToString());
            //---时间判断
            if (string.IsNullOrEmpty(sysConfig.timestyle))
            {
                time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
            }
            else
            {
                time = DateTime.Now.ToString(sysConfig.timestyle);
            }

            text = doReplace(text, "{time}", time);

            //---mappig
            text = doReplace(text, "{data}", data);
            text = doReplace(text, "{adata}", adata);
            text = doReplace(text, "{bdata}", bdata);




            //File.WriteAllText(Application.StartupPath + "\\mapping\\mapping.txt", text);
            //LogRecord.WriteMapping($"{StaInspect.Instance.loadPath}\\mapping", code, text);
            return text;

        }



    }
}

